/**
 * Copyright (c) 2012, SHX Studio.
 * All rights reserved.
 * rosary226@gmail.com
 * 
 * @author shenqianfeng
 * @date 2012-9-1  
 * @version 1.0   
 */


package com.xxx.sqfengine;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;
import android.opengl.GLU;

public class SQFGLRenderer implements GLSurfaceView.Renderer{

	private SQFGLScene mScene;
	private GL10 mGL;
	
	public SQFGLRenderer(SQFGLScene scene) {
		this.mScene = scene;
	}
	
	private void setGL(GL10 gl) {
		mGL = gl;
	}
	
	public void onDrawFrame(GL10 gl) {
		setGL(gl);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
		mScene.updateScene();
		drawScene();
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		
		setGL(gl);

		//GLU.gluLookAt(gl, 0.0f, 0.0f, 100.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 100.0f);
		gl.glViewport(0, 0, width, height);
		gl.glMatrixMode(GL10.GL_PROJECTION);
		gl.glLoadIdentity();
		GLU.gluPerspective(gl, 60.0f, (float)width/(float)height, 0.1f, 100.0f);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glLoadIdentity();
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		setGL(gl);
		mScene.initScene();
		initGLDrawing();
	}

	private void initGLDrawing() {
		mGL.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
		mGL.glShadeModel(GL10.GL_SMOOTH);
		mGL.glClearDepthf(1.0f);
		mGL.glEnable(GL10.GL_DEPTH_TEST);
		mGL.glDepthFunc(GL10.GL_LEQUAL);
		mGL.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
	}
	
	private void drawScene() {
		if(null == mGL) return;
		for (int i = 0; i < mScene.get3DObjectNum(); i++) {
			SQFGL3DObject obj = mScene.get3DObject(i);
			obj.draw(mGL);
		}
	}
	
	private void draw3DObject() {
		
	}
}
